package cn.fsd.filter.handler;

import cn.fsd.vo.Auth;
import cn.fsd.util.Constants;
import cn.fsd.util.JwtTokenUtil;
import cn.fsd.util.RedisUtil;
import java.util.List;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

@Component
@Slf4j
public class TokenAuthHandler {

  @Autowired
  JwtTokenUtil jwtTokenUtil;
  @Autowired
  RedisUtil redisUtil;

  public Auth authenticate(ServerWebExchange exchange) {
    ServerHttpRequest request = exchange.getRequest();
    List<String> headers = request.getHeaders().get("token");
    Auth auth = new Auth();
    if (headers != null && headers.size() > 0 && !StringUtils.isEmpty(headers.get(0))) {
      log.info("获取到的 headerToken = " + headers.get(0));
      String headerToken = headers.get(0);

      // postMan测试时,自动加入的前缀,要去掉。
      String token = headerToken.replace("Bearer", "").trim();

      //从redis获取存储的token
      String userName = (String) redisUtil.get(token);

      if(StringUtils.isEmpty(userName)){
        auth.authFailed("token认证失败");
      }else{
        auth.authSuccess("token认证成功");
        //刷新token的有效时间
        redisUtil.set(userName,token,Constants.TOKEN_EXPIRE);
      }
    } else {
      auth.authFailed(Constants.TOKEN_EMPTY);
    }
    return auth;
  }
}
